package sg4c.protocol;

import java.awt.event.KeyEvent;
import java.io.IOException;
import sg4c.frontend.RedirectingKeyListener;

public class KeyEventProtocol extends RedirectingKeyListener {

    private final DataOutputProtocol out;
    public static final int CMD_EVENT_KEY = 0xee20;
    public static final int CMD_EVENT_KEY_TYPED = 0xee21;
    public static final int CMD_EVENT_KEY_PRESSED = 0xee22;
    public static final int CMD_EVENT_KEY_RELEASED = 0xee23;

    public KeyEventProtocol(DataOutputProtocol out) {
        this.out = out;
    }

    @Override
    public void keyTyped(KeyEvent evt) {
        try {
            out.writeInt(CMD_EVENT_KEY);
            out.writeInt(CMD_EVENT_KEY_TYPED);
            //out.writeString(".event.key.typed");
            out.writeInt(evt.getKeyChar());
            out.writeInt(evt.getKeyCode());
            evt.consume();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void keyPressed(KeyEvent evt) {
        try {
            out.writeInt(CMD_EVENT_KEY);
            out.writeInt(CMD_EVENT_KEY_PRESSED);
            //out.writeString(".event.key.pressed");
            out.writeInt(evt.getKeyChar());
            out.writeInt(evt.getKeyCode());
            evt.consume();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void keyReleased(KeyEvent evt) {
        try {
            out.writeInt(CMD_EVENT_KEY);
            out.writeInt(CMD_EVENT_KEY_RELEASED);
            //out.writeString(".event.key.released");
            out.writeInt(evt.getKeyChar());
            out.writeInt(evt.getKeyCode());
            evt.consume();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }
}
